﻿using iTool.Cloud.Center;
using iTool.Cloud.Center.Model;
using iTool.Clustering.Center.ServiceProvider;
using iTool.Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using Orleans.Messaging;
using Orleans.Runtime.Membership;
using System;

namespace iTool.Clustering.Center
{
    public static class iToolGatewayClientExtensions
    {
        private static IClusterClient SetiCenterClustering(ClusteringStaticOptions configureOptions)
        {
            iPrint.Line("\niTool> Connectioning iToolCenter...");
            var clientBuilder = new ClientBuilder();

            clientBuilder.Configure<ClusterOptions>(options =>
            {
                options.ClusterId = configureOptions.ClusterOptions.ClusterId;
                options.ServiceId = configureOptions.ClusterOptions.ServiceId;
            });

            clientBuilder.UseStaticClustering(options =>
            {
                options.Gateways = configureOptions.GetGatewayUris();
            });

            clientBuilder.ConfigureApplicationParts(parts => 
                parts.AddApplicationPart(typeof(ClusterClientService).Assembly)
                .WithCodeGeneration()
                .WithReferences());

            var client = clientBuilder.Build();
            client.Connect().Wait();
            iPrint.Success("\niTool> Connectioned successfully.");
            return client;

        }

        public static IClientBuilder UseiCenterClustering(this IClientBuilder builder, ClusteringStaticOptions configureOptions)
        {
            var client = SetiCenterClustering(configureOptions);

            // 避免对象冲突
            iCenterClusterClient clusterClient = new CenterClusterClient(client);
            builder.ConfigureServices(services => services.AddSingleton(clusterClient));
            return builder.ConfigureServices(services => services.AddSingleton<IGatewayListProvider, iCenterGatewayListProvider>());
        }
    }
}
